package com.j.lemon.learn.basic.httpClient;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

class PostDemo2 {
    private static final String URL = "https://apiqa.st-creditech.com/file/external/fileDownload";
    @Test
    void test1() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> list = new ArrayList<>();
        //partner_code
        list.add(new BasicNameValuePair("partner_code","XXX"));
        //partner_key
        list.add(new BasicNameValuePair("partner_key","XXX"));
        //app_type(固定="file")
        list.add(new BasicNameValuePair("app_type","file"));
        //文件名称，调用方自定义即可
        list.add(new BasicNameValuePair("file_name","test.docx"));
        //文件uuid_name
        list.add(new BasicNameValuePair("uuid_name","608d779caa0341019634b8dbdbae913d.docx"));
        
        UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
        HttpPost httpPost=new HttpPost(URL);
        RequestConfig config = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(2000).build();
        httpPost.setEntity(encodedFormEntity);
        httpPost.setConfig(config);
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity entity=httpResponse.getEntity();



        //获取流
        InputStream content = entity.getContent();

        //将流写入本地文件(word文档)
        File file = new File("/Users/lijunjun/work/授权书2.docx");
        if(!file.exists()){
            file.createNewFile();
        }
        OutputStream outputStream = Files.newOutputStream(file.toPath());
        XWPFDocument xdoc = new XWPFDocument(content);
        xdoc.write(outputStream);
    }
}
